//权限路由处理函数模块
const db = require('../db/index')
const util = require('util')
const { string } = require('joi')
const query = util.promisify(db.query).bind(db)
    //自定义函数
function getTree(result, keyId) {
    //生成一次菜单
    let arr = []
    for (idx in result) {
        if (result[idx].ps_level == 0) {
            if (keyId.length !== 0 && keyId.indexOf(result[idx].ps_id + '') == -1) {
                continue
            }
            arr.push({
                id: result[idx].ps_id,
                authName: result[idx].ps_name,
                path: result[idx].ps_api_path,
                pid: result[idx].ps_pid,
                children: []
            })
        }
    }
    //生成二级菜单
    for (idx in result) {
        if (result[idx].ps_level == 1) {
            for (var j = 0; j < arr.length; j++) {
                if (result[idx]['ps_pid'] == arr[j].id) {
                    if (keyId.length !== 0 && keyId.indexOf(result[idx].ps_id + '') == -1) {
                        continue
                    }
                    arr[j].children.push({
                        id: result[idx].ps_id,
                        authName: result[idx].ps_name,
                        path: result[idx].ps_api_path,
                        pid: result[idx].ps_pid,
                        children: []
                    })
                }
            }
        }
    }
    //生成三级菜单
    for (idx in result) {
        if (result[idx].ps_level == 2) {
            for (var j = 0; j < arr.length; j++) { //找一级菜单
                var secondMenu = arr[j].children //二级菜单
                for (var i = 0; i < secondMenu.length; i++) { //找出二级菜单里的每一项
                    if (result[idx]['ps_pid'] == secondMenu[i].id) {
                        if (keyId.length !== 0 && keyId.indexOf(result[idx].ps_id + '') == -1) {
                            continue
                        }
                        secondMenu[i].children.push({
                            id: result[idx].ps_id,
                            authName: result[idx].ps_name,
                            path: result[idx].ps_api_path,
                            pid: result[idx].ps_pid + ',' + arr[j].id
                        })
                    }
                }
            }
        }
    }
    return arr
}
//权限列表
exports.getPower = (req, res) => {
        // res.ResData("获取权限列表")
        //接收参数
        let type = req.params.type
            // res.ResData(type)
            //判断参数类型
        if (!type || type != "list" && type != "tree")
            return res.ResData("参数错误!")
                //操作数据库
                // var sql = "select * from sp_permission,sp_permission_api where sp_permission.ps_id=sp_permission_api.ps_id"
        var sql = "select e.ps_id,e.ps_name,e.ps_pid,e.ps_level,d.ps_api_path from sp_permission e left join sp_permission_api d on(e.ps_id=d.ps_id)"
        db.query(sql, (err, result) => {
            if (err) return res.ResData("获取权限信息失败！")
                // res.ResData(result)
            if (type == 'list') {
                var retPowers = []
                for (idx in result) {
                    var manager = result[idx];
                    retPowers.push({
                        "id": manager.ps_id,
                        "authName": manager.ps_name,
                        "level": manager.ps_level,
                        "pid": manager.ps_pid,
                        "path": manager.ps_api_path
                    })
                }
                res.ResData("获取权限信息成功", 200, retPowers)
            } else {
                var arr = getTree(result, [])
                res.ResData("获取权限信息成功", 200, arr)
            }
        })
    }
    // 角色列表
exports.rolesList = async(req, res) => {
        // res.ResData("角色列表")
        //角色列表查询角色
        var sql1 = "select * from sp_role"
        var sql2 = "select e.ps_id,e.ps_name,e.ps_pid,e.ps_level,d.ps_api_path from sp_permission e left join sp_permission_api d on(e.ps_id=d.ps_id)"
        try {
            var result2 = await query(sql2)
            var result1 = await query(sql1)
                // console.log(result2);
            let arr = []
            for (idx in result1) {
                let keyId = result1[idx]['ps_ids'].split(",")
                    // console.log(keyId);
                let obj = {
                    "id": result1[idx].role_id,
                    "roleName": result1[idx].role_name,
                    "roleDesc": result1[idx].role_desc,
                    "children": []
                }
                let tree = getTree(result2, keyId)
                obj.children = tree
                arr.push(obj)
            }
            res.ResData("获取角色列表成功", 200, arr)
        } catch (err) {
            res.ResData(err);
            // console.log(err);
        }
    }
    //添加角色
exports.addRoles = (req, res) => {
        // res.ResData("添加角色")
        //1.获取数据
        // console.log(req.body);
        var role_name = req.body.roleName
        var role_desc = req.body.roleDesc
            //2.检查用户名是否存在
        var sql = "select * from sp_role where role_name=?"
        db.query(sql, role_name, (err, result) => {
            if (err) return res.ResData("添加失败!")
            if (result.length > 0) return res.ResData("用户名已存在!")
                //3.添加数据
            var sql = "insert into sp_role (role_name,role_desc)values(?,?)"
            db.query(sql, [role_name, role_desc], (err, data) => {
                if (err) return res.ResData("添加失败!")
                var sql = "select * from sp_role where role_name=?"
                db.query(sql, role_name, (err, result) => {
                    if (err) return res.ResData("获取信息失败!")
                    res.ResData("添加用户成功", 200, {
                        "roleId": result[0].role_id,
                        "roleName": role_name,
                        "roleDesc": role_desc
                    })
                })
            })
        })
    }
    //根据 ID 查询角色
exports.searchRoles = (req, res) => {
        // res.ResData("查询角色")
        //1.接收参数
        var id = req.params.id
            //2.查询用户信息
        var sql = "select * from sp_role where role_id=?"
        db.query(sql, id, (err, result) => {
            if (err) return res.ResData("角色查询失败!")
                //3.返回结果
            if (result.length > 0) {
                res.ResData("角色查询成功", 200, {
                    "roleId": result[0].role_id,
                    "roleName": result[0].role_name,
                    "roleDesc": result[0].role_desc
                })
            } else {
                res.ResData('用户查询失败')
            }
        })
    }
    //编辑提交角色
exports.updateRoles = (req, res) => {
        // res.ResData("编辑")
        //1.接收参数
        var id = req.params.id
        var roleName = req.body.roleName
        var roleDesc = req.body.roleDesc
            //2.更新数据
        var sql = "update sp_role set role_name=?, role_desc=? where role_id=?"
        db.query(sql, [roleName, roleDesc, id], (err, result) => {
            if (err) return res.ResData("更新角色信息失败!", err)
                // console.log(result);
            if (result.affectedRows < 1) return res.ResData("更新角色信息失败!")
            var sql = "select * from sp_role where role_id=?"
                //3.返回结果
            db.query(sql, id, (err, resResult) => {
                if (err) return res.ResData("信息读取失败", err)
                res.ResData("更新用户信息成功", 200, {
                    "id": resResult[0].mg_id,
                    "username": resResult[0].mg_name,
                    "role_id": resResult[0].role_id,
                    "mobile": resResult[0].mg_mobile,
                    "email": resResult[0].mg_email
                })
            })
        })
    }
    //删除角色
exports.deleteRoles = (req, res) => {
        // res.ResData("删除角色")
        var id = req.params.id
        var sql = "delete from sp_role where role_id=?"
        db.query(sql, id, (err, result) => {
            if (err) return ResData("删除角色失败!")
            if (result.affectedRows != 1) return ResData("删除角色失败!")
            res.ResData("删除成功", 200)
        })
    }
    //角色授权
exports.updateRids = (req, res) => {
        // res.ResData("角色授权")
        //获取角色id
        const roleId = req.params.roleId
            //参数验证
        if (roleId.trim() == ' ') return res.ResData("角色id不能为空!")
            // if (parseInt(roleId) != roleId) return res.ResData("角色id必须是整数!")
            // if (typeof(roleId) != 'number') return res.ResData("角色id必须是数字!")
        if (roleId.indexOf('.') != -1) return res.ResData("角色id必须是整数!")
        if (parseInt(roleId) != roleId) return res.ResData("角色id必须是数字!")
            //处理逻辑
        var sql = "update sp_role set ps_ids=? where role_id=?"
        db.query(sql, [req.body.rids, roleId], (err, result) => {
            if (err) return res.ResData("角色授权失败!")
            res.ResData("授权成功!", 200)
        })
    }
    //删除角色指定权限
exports.deleteRids = async(req, res) => {
    // res.ResData("删除角色指定权限")
    //参数验证
    const roleId = req.params.roleId
        //获取权限id
    const rightId = req.params.rightId
    if (roleId.trim() == '') return res.ResData("角色id不能为空!")
    if (roleId.indexOf('.') != -1) return res.ResData("角色id必须是整数!")
    if (parseInt(roleId) != roleId) return res.ResData("角色id必须是数字!")
    if (rightId.trim() == '') return res.ResData("权限id不能为空!")
    if (rightId.indexOf('.') != -1) return res.ResData("权限id必须是整数!")
    if (parseInt(rightId) != rightId) return res.ResData("权限id必须是数字!")
        //逻辑
    var sql = "select * from sp_role where role_id=?"
    try {
        var result = await query(sql, roleId)
        ps_ids = result[0].ps_ids.split(',')
        new_ps_ids = []
        for (idx in ps_ids) {
            ps_id = ps_ids[idx]
            if (rightId == ps_id) {
                continue
            }
            new_ps_ids.push(ps_id)
        }
        // console.log(new_ps_ids);
        new_ps_ids = new_ps_ids.join(',')
            //更新数据
        var updataSql = "update sp_role set ps_ids=? where role_id=?"
        var result2 = await query(updataSql, [new_ps_ids, roleId])
        var sql2 = "select e.ps_id,e.ps_name,e.ps_pid,e.ps_level,d.ps_api_path from sp_permission e left join sp_permission_api d on(e.ps_id=d.ps_id)"
        var data = await query(sql2)
        tree = getTree(data, new_ps_ids)
        res.ResData("取消权限成功", 200, tree)
    } catch (err) {
        res.ResData("权限删除失败!")
    }
    // db.query(sql, roleId, (err, result) => {
    //     if (err) return res.ResData("获取权限信息失败!")
    //     ps_ids = result[0].ps_ids.split(',')
    //     new_ps_ids = []
    //     for (idx in ps_ids) {
    //         ps_id = ps_ids[idx]
    //         if (rightId == ps_id) {
    //             continue
    //         }
    //         new_ps_ids.push(ps_id)
    //     }
    //     // console.log(new_ps_ids);
    //     new_ps_ids = new_ps_ids.join(',')
    //         //更新数据
    //     var sql = "update sp_role set ps_ids=? where role_id=?"
    //     db.query(sql, [new_ps_ids, roleId], (err, result) => {
    //         if (err) return res.ResData("权限删除失败!")
    //             // res.ResData("角色权限删除成功!", 200)
    //         var sql2 = "select e.ps_id,e.ps_name,e.ps_pid,e.ps_level,d.ps_api_path from sp_permission e left join sp_permission_api d on(e.ps_id=d.ps_id)"
    //         db.query(sql2, (err, data) => {
    //             tree = getTree(data, new_ps_ids)
    //             res.ResData("成功", 200, tree)
    //         })
    //     })
    // })
}